package jvm;

import java.util.concurrent.TimeUnit;

public class SimpleHappenBefore {


  public static void main(String[] args) throws InterruptedException {

    //由于多线程情况下未必会试出重排序的结论,所以多试一些次
    for (int i = 0; i < 1000000; i++) {
      TimeUnit.MILLISECONDS.sleep(100);
      SimpleHappenBefore simpleHappenBefore = new SimpleHappenBefore();
      Thread threadA = new Thread(new Runnable() {
        @Override
        public void run() {
          simpleHappenBefore.write();
        }
      });

      Thread threadB = new Thread(new Runnable() {
        @Override
        public void run() {
          simpleHappenBefore.read();
        }
      });

      threadA.start();
      threadB.start();

      //这里等待线程结束后,重置共享变量,以使验证结果的工作变得简单些.
      threadA.join();
      threadB.join();

      if (simpleHappenBefore.flag) {
        break;
      }

    }

  }

  /**
   * 这是一个验证结果的变量
   */
  private int a = 0;
  private int b = 0;
  private int c = 0;
  private int d = 0;

  boolean flag = false;

  public void write() {
    a = 1;
    b = 1;
    c = 1;
    d = 1;
  }

  public void read() {

    if (b == 1 && a == 0) {
      System.out.println("a == 0");
      flag = true;
    } else if (c == 1 && (b == 0 || a == 0)) {
      System.out.println("b == 0 || a == 0");
      flag = true;
    } else if (d == 1 && (c == 0 || b == 0 || a == 0)) {
      System.out.println("c == 0 || b == 0 || a == 0");
      flag = true;
    }
    flag = false;

  }

}